<?php

namespace App\Http\Controllers\Utility;

use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Validation\Rule;
use App\Services\HelpTutorialService;
use App\HelpTutorial;

class HelpTutorialController extends Controller
{
    private $helpTutorialService = null;

    public function __construct(HelpTutorialService $helpTutorialService)
    {
        $this->helpTutorialService = $helpTutorialService;
    }

    public function index()
    {
        return view('utility.helptutorial.helptutorial');
    }

    public function getInitTutorialTrees()
    {
        return $this->helpTutorialService->getCascadeTutorials();
    }

    public function query(Request $request)
    {
        return $this->helpTutorialService
            ->getHelpTutorials($request->all());
    }

    public function createTutorial($parentId)
    {
        if (!empty($parentId)) {
            $parent = HelpTutorial::findOrFail($parentId);
        } else {
            $parent = null;
        }
        return view('utility.helptutorial.create', [
            'parentId' => $parentId,
            'possiableParents' => $this->helpTutorialService->getPossiableParentTutorials($parent),
        ]);
    }

    public function saveNewTutorial(Request $request)
    {
        $input = $request->all();

        $this->validateWhenSaveNewTutorial($input);

        $this->helpTutorialService->saveNewTutorial($input, $input['sub_images'], $input['guidField']);

        return response()->json([
            'Success' => true,
            'Message' => '新增主题成功',
        ]);
    }

    public function editTutorial($tutorialId)
    {
        $tutorial = HelpTutorial::findOrFail($tutorialId);
        if (isset($tutorial->parent_id)) {
            $parentId = $tutorial->parent_id;
        } else {
            $parentId = 0;
        }

        $possiableParents = $this->helpTutorialService->getPossiableParentTutorialsExceptSelf($tutorialId);

        return view('utility.helptutorial.create', [
            'parentId' => $parentId,
            'possiableParents' => $possiableParents,
            'tutorial' => $tutorial
        ]);
    }

    public function saveUpdateTutorial(Request $request)
    {
        $input = $request->all();

        $this->validateWhenSaveUpdateTutorial($input);

        $tutorial = HelpTutorial::findOrFail($input['id']);
        $tutorial->update([
            'id' => $input['id'],
            'title' => $input['title'],
            'content' => $input['content'],
            'parent_id' => !empty($input['parent_id'])?$input['parent_id']:null,
            'sort_order' => $input['sort_order']
        ]);

        return response()->json([
            'Success' => true,
            'Message' => '修改主题内容成功',
        ]);
    }

    public function deleteTutorial(Request $request)
    {
        $input = $request->all();

        $this->validateWhenDeleteTutorial($input);

        $tutorial = HelpTutorial::findOrFail($input['id']);
        $tutorial->delete();

        return response()->json([
            'Success' => true,
            'Message' => '删除主题内容成功',
        ]);
    }

    public function getTutorialDetail($tutorialId)
    {
        return view('utility.helptutorial.modifyimage', [
            'tutorialId' => $tutorialId
        ]);
    }

    public function getTutorialDetailImages($tutorialId)
    {
        return $this->helpTutorialService
            ->getHelpTutorialImages(['tutorial_id' => $tutorialId], false);
    }

    public function deleteTutorialImage($tutorialImageId)
    {
        $this->helpTutorialService
            ->deleteTutorialImage($tutorialImageId);

        return response()->json([
            'Success' => true,
            'Message' => '删除主题图片成功',
        ]);
    }

    public function addTutorialImage(Request $request)
    {
        $input = $request->all();

        $this->helpTutorialService
            ->addTutorialImage($input['tutorial_id'], $input['image_file_id']);

        return response()->json([
            'Success' => true,
            'Message' => '添加主题图片成功',
        ]);
    }

    private function getPossiableTutorialIdsWhenUpdate($tutorialId)
    {
        $possiableTutorialIds = array_values($this->helpTutorialService->getPossiableParentTutorialsExceptSelf($tutorialId)
            ->pluck('id')->toArray());

        array_push($possiableTutorialIds, 0);

        return $possiableTutorialIds;
    }

    private function validateWhenSaveUpdateTutorial(Array $input)
    {
        return Validator::make($input, [
            'title' => [
                'required',
                'max:50'
            ],
            'parent_id' => [
                Rule::in($this->getPossiableTutorialIdsWhenUpdate($input['id']))
            ],
            'content' => 'required|max:8000',
            'sort_order' => 'required|numeric'
        ], [
            'title.required' => '素材主题不可为空',
            'title.max' => '素材主题长度不可超过:max',
            'parent_id.in' => '传入的父级id不合法',
            'content.required' => '内容不可为空',
            'content.max' => '内容长度不可超过:max',
            'sort_order.required' => '必须传入同级排序号',
            'sort_order.numeric' => '同级排序号必须为数字'
        ])->validate();
    }

    private function getPossiableParentIds()
    {
        $tutorialIds = HelpTutorial::all()->pluck('id')->toArray();
        array_push($tutorialIds, 0);
        return $tutorialIds;
    }

    private function validateWhenSaveNewTutorial(Array $input)
    {
        return Validator::make($input, [
            'title' => 'required|max:50',
            'parent_id' => [
                Rule::in($this->getPossiableParentIds())
            ],
            'content' => 'required|max:8000',
            'sort_order' => 'required|numeric',
            //'sub_images' => 'required',
        ], [
            'title.required' => '素材主题不可为空',
            'title.max' => '素材主题长度不可超过:max',
            'parent_id.in' => '传入的父级id不合法',
            'content.required' => '内容不可为空',
            'content.max' => '内容长度不可超过:max',
            'sort_order.required' => '必须传入同级排序号',
            'sort_order.numeric' => '同级排序号必须为数字',
            //'sub_images.required' => '必须传入项目素材图片'
        ])->validate();
    }

    private function validateWhenDeleteTutorial(Array $input)
    {
        return Validator::make($input, [
                'id' => 'required|exists:help_tutorials,id'
            ], [
                'id.required' => '必须传入主题条目ID',
                'id.exists' => '该主题条目ID参数有误，不存在'
            ])->after(function ($validator) use($input) {
                if ($this->helpTutorialService->hasChildren($input['id'])) {
                    $validator->errors()->add('id', '该主题条目存在子条目，不可删除');
                }
            })->validate();
    }
}
